﻿using Microsoft.AspNetCore.Http;
using System.Text;

namespace Infrastructure.Extension
{
    public static class HttpContextExtension
    {
        public static string GetUserIp(this HttpContext context)
        {
            var ip = $"{context.Request.Headers["X-Forwarded-For"].FirstOrDefault()}|{Convert.ToString(context.Connection.RemoteIpAddress)}";
            //if (string.IsNullOrEmpty(ip)) ip = Convert.ToString(context.Connection.RemoteIpAddress);
            return ip;
        }

        public static string GetAbsoluteUri(this HttpRequest request)
        {
            return new StringBuilder()
                .Append(request.Scheme)
                .Append("://")
                .Append(request.Host)
                .Append(request.PathBase)
                .Append(request.Path)
                .Append(request.QueryString)
                .ToString();
        }

        public static async Task<string> ReadBodyAsStringAsync(this HttpRequest request)
        {
            request.EnableBuffering();
            var requestReader = new StreamReader(request.Body);
            var requestBody = await requestReader.ReadToEndAsync();
            request.Body.Position = 0;
            return requestBody;
        }
    }
}
